package com.ruoyi.srmcontract.service.impl;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.google.common.base.Joiner;
import com.ruoyi.common.constant.Constants;

import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;

import com.ruoyi.srmcontract.domain.JacContracttemplate;
import com.ruoyi.srmcontract.mapper.JacContractMapper;
import com.ruoyi.srmcontract.mapper.JacContracttemplateMapper;
import com.ruoyi.srmcontract.service.IJacContracttemplateService;

/**
 * 合同协议维护Service业务层处理
 * 
 * @author yanggongxiao
 * @date 2020-07-31
 */
@Service
public class JacContracttemplateServiceImpl implements IJacContracttemplateService 
{   
	private static final Logger log = LoggerFactory.getLogger(JacContractItemServiceImpl.class);
    @Autowired
    private JacContracttemplateMapper jacContracttemplateMapper;
    @Autowired
    private RedisTemplate<String, Object>   redisTemplate;
    @Autowired
    private JacContractMapper jacContractMapper;

    /**
     * 查询合同协议维护
     * 
     * @param contracttemplateId 合同协议维护ID
     * @return 合同协议维护
     */
    @Override
    public List<JacContracttemplate> selectJacContracttemplateById(Long contracttemplateId)
    {
        return jacContracttemplateMapper.selectJacContracttemplateById(contracttemplateId);
    }

    /**
     * 查询合同协议维护列表
     * 
     * @param jacContracttemplate 合同协议维护
     * @return 合同协议维护
     */
    @Override
    public List<JacContracttemplate> selectJacContracttemplateList(JacContracttemplate jacContracttemplate)
    {   
    	List<String> statuslist = jacContracttemplate.getStatuslist();
    	if (statuslist !=null && statuslist.size() > 0)
    	{
    	String status = "'"+StringUtils.join(statuslist,"','")+"'";
    	jacContracttemplate.setStatus(status);
    	}
        return jacContracttemplateMapper.selectJacContracttemplateList(jacContracttemplate);
    }
    
    /**
     * 查询合同协议维护列表
     * 
     * @param 查询合同协议维护列表(查询public状态的，绑定模板界面使用)
     * @return 合同协议维护
     */
    @Override
    public List<JacContracttemplate> selectTemByPublic(JacContracttemplate jacContracttemplate)
    {   
    	jacContracttemplate.setStatus("'"+"Publish"+"'");
        return jacContracttemplateMapper.selectJacContracttemplateList(jacContracttemplate);
    }
    
    /**
     * 通过redis自增生成合同模板号（如：HT202008030001）
     * 
     * @param Ht  合同号前缀
     * @return 合同号
     */
    public String createContractCode(String key) {
        //加上时间戳 如果不需要
        String datetime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //查询 key 是否存在， 不存在返回 1 ，存在的话则自增加1
        Long autoID = redisTemplate.opsForValue().increment(key + datetime, 1);
        //这里是 4 位id，如果位数不够可以自行修改 ，下面的意思是 得到上面 key 的 值，位数为 4 ，不够的话在左边补 0 ，比如  110 会变成  0110
        String value = StringUtils.leftPad(String.valueOf(autoID), 4, "0");
        //然后把 时间戳和优化后的 ID 拼接
        String code = MessageFormat.format("{0}{1}",  key + datetime,value);
        //设置三天过期
        redisTemplate.expire(key + datetime, 3,TimeUnit.DAYS);
        return code;
    }
    
    
    /**
     * 通过原合同模板代号复制合同
     * 
     * @param username：创建用户  datetime：创建时间  Addition2：新合同号
     * @return 插入条数
     */
    @Override
    public int copyContractModel(JacContracttemplate jacContracttemplate)
    {   
    	//从session获取当前用户id
        HttpServletRequest request = ServletUtils.getRequest();
        String user = request.getHeader(Constants.CURRENT_USERNAME);
        String username = jacContractMapper.selectUserNameById(request.getHeader(Constants.CURRENT_ID));
        String datedate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String datetime = new SimpleDateFormat("HHmmss").format(new Date());
      //  Long date = Long.valueOf(datetime);
        jacContracttemplate.setCreateusername(username);
        jacContracttemplate.setCreateuser(user);
        jacContracttemplate.setCreatedate(datedate);
        jacContracttemplate.setCreatetime(datetime);
        jacContracttemplate.setLoguser(user);
        jacContracttemplate.setLogusername(username);
        jacContracttemplate.setLogdate(datedate);
        jacContracttemplate.setLogtime(datetime);
        jacContracttemplate.setStatus("New");
        jacContracttemplate.setAddition2(createContractCode("CT"));
        
        if (StringUtils.isBlank(jacContracttemplate.getDepartmentcode()))
        {
        	return jacContracttemplateMapper.copyContractModel(jacContracttemplate);
        }
        else
        {
        	return jacContracttemplateMapper.copyContractModelChange(jacContracttemplate);
        }	
    }
    
    /**
     * 通过合同模板号查询合同协议详情
     * 
     * @param contracttmpcode  合同模板号
     * @return 合同协议详情
     */
    @Override
    public String selectDetailByCode(String contracttmpcode) {
    	
    	return jacContracttemplateMapper.selectDetailByCode(contracttmpcode);
    }

    /**
     * 新增合同协议维护
     * 
     * @param jacContracttemplate 合同协议维护
     * @return 结果
     */
    @Override
    public int insertJacContracttemplate(JacContracttemplate jacContracttemplate)
    {   
    	//从session获取当前用户id
        HttpServletRequest request = ServletUtils.getRequest();
        String user = request.getHeader(Constants.CURRENT_USERNAME);
        String username = jacContractMapper.selectUserNameById(request.getHeader(Constants.CURRENT_ID));
        String datedate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String datetime = new SimpleDateFormat("HHmmss").format(new Date());
      //  Long date = Long.valueOf(datetime);
        jacContracttemplate.setCreateusername(username);
        jacContracttemplate.setCreateuser(user);
        jacContracttemplate.setCreatedate(datedate);
        jacContracttemplate.setCreatetime(datetime);
        jacContracttemplate.setLogusername(username);
        jacContracttemplate.setLoguser(user);
        jacContracttemplate.setLogdate(datedate);
        jacContracttemplate.setLogtime(datetime);
        jacContracttemplate.setStatus("New");
        return jacContracttemplateMapper.insertJacContracttemplate(jacContracttemplate);
    }

    /**
     * 修改合同协议维护
     * 
     * @param jacContracttemplate 合同协议维护
     * @return 结果
     */
    @Override
    public int updateJacContracttemplate(JacContracttemplate jacContracttemplate)
    {   
        HttpServletRequest request = ServletUtils.getRequest();
        String user = request.getHeader(Constants.CURRENT_USERNAME);
        String username = jacContractMapper.selectUserNameById(request.getHeader(Constants.CURRENT_ID));
        String datedate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String datetime = new SimpleDateFormat("HHmmss").format(new Date());
        jacContracttemplate.setLogdate(datedate);
        jacContracttemplate.setLogtime(datetime);
        jacContracttemplate.setLoguser(user);
        jacContracttemplate.setLogusername(username);
        return jacContracttemplateMapper.updateJacContracttemplate(jacContracttemplate);
        
    }
    
    /**
     * 修改合同模板状态
     * 
     * @param contracttemplateId 合同模板id
     * @return 状态
     */
    @Override
    public String updateTemStatus(Map<String, List<JacContracttemplate>> datas)
    {   
    	List<JacContracttemplate> jacContracttemplates = datas.get("datas");
    	List<String> statusCheck = new ArrayList<>();
    	String result = "1";
    	
    	for (JacContracttemplate jacContracttemplate : jacContracttemplates)
    	{
    	   String status = statusCheck(jacContracttemplate.getContracttemplateId(),jacContracttemplate.getStatus());
    	if ( !"1".equals(status))
    	{
    		statusCheck.add(jacContracttemplate.getContracttmpcode() + "更改状态失败！" +status);
    	}
    	else
    	{   
            HttpServletRequest request = ServletUtils.getRequest();
            String user = request.getHeader(Constants.CURRENT_USERNAME);
            String username = jacContractMapper.selectUserNameById(request.getHeader(Constants.CURRENT_ID));
            String datedate = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String datetime = new SimpleDateFormat("HHmmss").format(new Date());
            jacContracttemplate.setLogdate(datedate);
            jacContracttemplate.setLogtime(datetime);
            jacContracttemplate.setLoguser(user);
            jacContracttemplate.setLogusername(username);
			try {
				 jacContracttemplateMapper.updateJacContracttemplate(jacContracttemplate);
			} catch (Exception e) {
				log.error(jacContracttemplate.getCompanycode()+"更改合同模板状态失败",e);
				return "更改合同模板状态失败，请联系管理员！";
			}
    	}
    	}
		if (statusCheck.size() > 0 && statusCheck != null)
		{
			result = Joiner.on(';').join(statusCheck);
		}
		return result;
    }

    
    public String statusCheck(Long contracttemplateId,String status) 
    {
        String s = jacContracttemplateMapper.checkStatus(contracttemplateId);
    	if ("Publish".equals(status) && !"New".equals(s))
    	{
    		return "只有新增状态允许发布！";
    	}
    	if ("Cancel".equals(status))
    	{
      		if ("New".equals(s))
    		{
    		return "模板为新增状态，不能废止，请直接删除！";
    		}
      		if (!"Publish".equals(s))
    		{
    		return "只有发布状态允许废止！";
    		}
      		else
      		{
      			return "1";
      		}
    	}
    	else
    	{
    		return "1";
    	}
    }
    
    /**
     * 删除合同协议维护对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public String deleteJacContracttemplateByIds(String ids)
    {    
    	String result = "1";
    	List<String> checkTemUse = new ArrayList<>();
    	String[] id = ids.split(",");
    	for ( String contracttemplateId : id)
    	{   
    		String contracttmpcode = jacContracttemplateMapper.checkTemUse(Long.valueOf(contracttemplateId));
    		if ( !StringUtils.isBlank(contracttmpcode) && !"".equals(contracttmpcode))
    		{
    			checkTemUse.add(contracttmpcode); 
    		}
    		else {
    			int j = jacContracttemplateMapper.deleteJacContracttemplateById(Long.valueOf(contracttemplateId));
        		if ( j > 0)
        		{
        			result = "1";
        		}
        		else
        		{
        			result = "合同模板" + contracttmpcode + "删除失败，请联系管理员！";
        		}
			}
    	}
   		if (checkTemUse.size() > 0 && checkTemUse != null)
		{
			result = "合同模板" + Joiner.on(",").join(checkTemUse) + "已经在合同中使用，不允许删除！" ;
			log.info(result);
			return result;
		}
        return result;
    }

    /**
     * 删除合同协议维护信息
     * 
     * @param contracttemplateId 合同协议维护ID
     * @return 结果
     */
    public int deleteJacContracttemplateById(Long contracttemplateId)
    {   
    	/*jacContracttemplateMapper.checkTemUse()*/
    	// 批量删除
    	/*return jacContracttemplateMapper.deleteJacContracttemplateByIds(Convert.toStrArray(ids))*/
        return jacContracttemplateMapper.deleteJacContracttemplateById(contracttemplateId);
    }
}
